package com.baiyinet.util.webview;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.content.ClipboardManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;

import com.baiyinet.BuildConfig;
import com.baiyinet.Constants;
import com.baiyinet.Constants.PATH;
import com.baiyinet.R;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.biz.PageStatus;
import com.baiyinet.pay.PayUtils;
import com.baiyinet.rest.ApiHelper;
import com.baiyinet.rest.Link;
import com.baiyinet.ui.ToolbarOwner;
import com.baiyinet.ui.general.GeneralActivity_;
import com.baiyinet.ui.player.AliyunPlayerActivity;
import com.baiyinet.ui.player.AliyunPlayerActivity_;
import com.baiyinet.ui.share.ShareLinkDialogActivity;
import com.baiyinet.ui.share.ShareModeDialogActivity;
import com.baiyinet.ui.main.MainActivity_;
import com.baiyinet.util.AppUtils;
import com.baiyinet.util.CookieHelper;
import com.baiyinet.util.DialogUtils;
import com.baiyinet.util.IntentUtils;
import com.baiyinet.util.ShareUtils;
import com.baiyinet.util.Utils;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.github.ybq.android.spinkit.SpinKitView;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import cn.jpush.android.api.JPushInterface;
import me.nereo.multi_image_selector.MultiImageSelector;

import static com.baiyinet.ui.general.GeneralActivity.REQUEST_IMAGE;

/**
 * 在应用中加载页面
 *
 * @author J.Huang
 * @version 1.0
 * @since 16/12/13
 */
public class GeneralWebViewClient extends BaseWebViewClient {

    private Activity mActivity;
    private Fragment mFragment;
    private WebView mWebView;
    private SpinKitView mLoadingIndicator;
    private CurrentUser mCurrentUser;
    private ApiHelper mApiHelper;

    // 分享
    public static String sShareTitle;
    public static String sShareContent;
    private static String sShareUrl;
    private static String sShareIconUrl;

    private boolean mClearHistoryFlag = false;

    private ToolbarOwner.IToolbar mToolbar;
    private String title;
    private String content;
    private String shareUrl;
    private String iconUrl;
    private String timelineFun;
    private String timelineMode;

    GeneralWebViewClient(Fragment fragment,
                         ToolbarOwner.IToolbar toolbar,
                         String loadUrl,
                         WebView webView,
                         SpinKitView loadingIndicator,
                         CurrentUser currentUser,
                         ApiHelper apiHelper) {
        super(loadUrl);
        mFragment = fragment;
        mToolbar = toolbar;
        mActivity = fragment.getActivity();
        mWebView = webView;
        mLoadingIndicator = loadingIndicator;
        mCurrentUser = currentUser;
        mApiHelper = apiHelper;
    }

    public GeneralWebViewClient(Activity activity,
                         ToolbarOwner.IToolbar toolbar,
                         String loadUrl,
                         WebView webView,
                         SpinKitView loadingIndicator,
                         CurrentUser currentUser,
                         ApiHelper apiHelper) {
        super(loadUrl);
        mActivity = activity;
        mToolbar = toolbar;
        mFragment = null;
        mWebView = webView;
        mLoadingIndicator = loadingIndicator;
        mCurrentUser = currentUser;
        mApiHelper = apiHelper;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        if (mLoadingIndicator != null) {
            mLoadingIndicator.setVisibility(View.VISIBLE);
        }

//        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE,null);
//        mWebView.setVisibility(View.INVISIBLE);

        if (url.startsWith("http")) {
            if (mActivity instanceof GeneralActivity_) {
                ((GeneralActivity_) mActivity).setLastValidUrl(url);
            }else  if (mActivity instanceof MainActivity_) {
                ((MainActivity_) mActivity).setLastValidUrl(url);
            }
        }

        try {
            if (mActivity instanceof GeneralActivity_) {
                if (url.contains("about:blank")) {
                    ((GeneralActivity_) mActivity).isNetworkConnectionFailed(true);
                } else {
                    ((GeneralActivity_) mActivity).isNetworkConnectionFailed(false);
                }
            }else if (mActivity instanceof MainActivity_) {
                if (url.contains("about:blank")) {
                    ((MainActivity_) mActivity).isNetworkConnectionFailed(true);
//                    Utils.UI.showToastShort("网络无链接");
                } else {
                    ((MainActivity_) mActivity).isNetworkConnectionFailed(false);
                }
            }

            if (url.contains("PageTitle")) {
                Uri uri = Uri.parse(url);
                String pageTitle = uri.getQueryParameter("PageTitle");
                if (mToolbar != null) {
                    mToolbar.setToolbarTitle(pageTitle);
                }
            }


            String completeCookie = mCurrentUser.getCompleteCookie();
            String currentCookie = CookieHelper.getWebViewRequestUrlCookie(mActivity, url);
            if (!TextUtils.isEmpty(completeCookie) && !TextUtils.isEmpty(currentCookie)) {
                if (!currentCookie.contains(completeCookie)) {
                    new WebViewTask(mActivity, view, url, mCurrentUser.getCurrentCookie()).execute();
                }
            }

        } catch (Exception e) {
        }

        super.onPageStarted(view, url, favicon);
    }

    private String decodeUrl(String url) {
        String result = url.replace("%%", "%25%");

        try {
            result = URLDecoder.decode(result, "UTF-8");
            result = URLDecoder.decode(result, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }

        return result;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if (url == null || TextUtils.isEmpty(url)) {
            return true;
        }

        String oriUrl = url;

        url = decodeUrl(url);

//        if (url.contains("/aliyun")) {
//            Intent intent = new Intent();
//            intent.setClass(mActivity, AliyunPlayerActivity_.class);
//            mActivity.startActivity(intent);
//        }

        if (mClearHistoryFlag) {
            view.clearHistory();
            mClearHistoryFlag = false;
        }

        // 下拉刷新
        if (oriUrl.equals(mWebView.getUrl())) {
            // 同步cookie?
            new WebViewTask(mActivity, view, oriUrl, mCurrentUser.getCurrentCookie()).execute();
//            CookieHelper.setWebViewRequestUrlCookie(mActivity, url, mCurrentUser.getCurrentCookie());

//            Map<String, String> cookies = new WeakHashMap<>();
//            cookies.put("AppOS", "Android");

            mClearHistoryFlag = true;

//            view.clearView();
//            view.loadUrl(url, cookies);
            return true;
        }

        String lowerCaseUrl = url.toLowerCase().trim();

        /**
         * 花椒直播特殊处理
         */
        // 第三方特殊协议不处理
        if (lowerCaseUrl.startsWith("huajiao:") || lowerCaseUrl.contains("http://www.huajiao.com/dl.php")) {
            return true;
        }

        if (lowerCaseUrl.startsWith("radio:")) {
            handleOpenPlayerAction(url);
            return true;
        }

        // 拨打电话
        if (lowerCaseUrl.startsWith("tel:")) {
            handlePhoneAction(url);
            return true;
        }

        // 分享
        if (lowerCaseUrl.startsWith("share:")) {
            if (!showStoragePermissionDialog()) {
                handleShareAction(url);
            }
            return true;
        }

        // 分享链接
        if (lowerCaseUrl.startsWith("sharelink:")) {
            if (Utils.isFastLoading()) {
                return true;
            }
            handleShareLinkAction();
            return true;
        }

        // 九宫图/多图分享
        if (lowerCaseUrl.startsWith("sharemultiimage:")) {
            if (!showStoragePermissionDialog()) {
                handleShareMultiImagesAction();
            }

            return true;
        }

        // 支付
        if (lowerCaseUrl.startsWith("pay:")) {
            handlePayAction(url);
            return true;
        }

        // 复制文本
        if (lowerCaseUrl.startsWith("copy:")) {
            handleCopyAction(url);
            return true;
        }

        // 上传图片
        if (lowerCaseUrl.startsWith("upload:")) {
            if (!showStoragePermissionDialog() && !showCameraPermissionDialog()) {
                handleImageUploadAction(url);
            }

            return true;
        }

        // 多图一键保存
        if (lowerCaseUrl.startsWith("download:")) {
//            handleShareAction(url,true);
            if (!showStoragePermissionDialog()) {
                handleImageOneKeySaveAllAction(url);
            }

            return true;
        }

        // 保存单张图片
        if (lowerCaseUrl.startsWith("imagesave:") || lowerCaseUrl.startsWith("saveimage:")) {
            if (!showStoragePermissionDialog()) {
                handleImageSaveOneAction(url);
            }

            return true;
        }

        // 打开直播
        if (lowerCaseUrl.startsWith("radio:")) {
            handleOpenPlayerAction(url);

            return true;
        }

        // 放在所有特殊操作之后，因为url中可能有js回调函数名(大小写敏感)

        Uri uri = Uri.parse(lowerCaseUrl);

        String path = uri.getPath();

        String pageName = uri.getQueryParameter("pagename");
//        if (mActivity instanceof GeneralActivity_) {
//            ((GeneralActivity_) mActivity).addPageName(pageName);
//        }

        String pageNav = uri.getQueryParameter("pagenav");
        if (pageNav == null) {
            pageNav = "";
        }

        // pagenav特殊处理
        if (pageNav.startsWith("back_")){
            pageNav = pageNav.replace("back_", "");
            if (!TextUtils.isEmpty(pageNav)) {
                mCurrentUser.setBackAction(pageNav, false);
                mActivity.finish();
                return true;
            }
        } else if (pageNav.startsWith("backreload_")) {
            pageNav = pageNav.replace("backreload_", "");
            if (!TextUtils.isEmpty(pageNav)) {
                mCurrentUser.setBackAction(pageNav, true);
                mActivity.finish();
                return true;
            }
        }

        if (lowerCaseUrl.contains("h.huajiao.com") && lowerCaseUrl.contains("?liveid=")) {
            pageNav = "farword";
        }

        // 同步Cookie
        if ("root".equals(pageNav) || "home_index".equalsIgnoreCase(pageName)) {
            // 获取当前URL的CookieInfo保存到本地数据库
            String cookie = CookieHelper.getWebViewRequestUrlCookie(mActivity, url);

            if (!cookie.isEmpty()) {
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mActivity);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(Constants.KEY_COOKIE, cookie);
                editor.apply();
            }
        }

        CookieHelper.setWebViewRequestUrlCookie(mActivity, url, mCurrentUser.getCurrentCookie());

        // TODO: server returns wrong "farword", should be "forward"
        if ("蚂蚁助企".equals(mActivity.getString(R.string.app_name))) {
            if (TextUtils.isEmpty(pageNav)) {
                pageNav = "farword";
            }
        }

        switch (pageNav) {
            case "farword":
                if (Utils.isFastLoading()) {
                    return true;
                }

                String addLinkName = "";
                String addLinkUrl = "";
                String addLinkCode = uri.getQueryParameter("addlink");
                if (addLinkCode != null) {
                    for (Link addLink : mCurrentUser.getAddLinkList()) {
                        if (addLink.Code.toLowerCase().equals(addLinkCode)) {
                            addLinkName = addLink.Name;
                            addLinkUrl = addLink.Url;
                            break;
                        }
                    }
                }

                // 局部登录页面处理
                switch (path) {
                    case PATH.LOGIN:
                        // FIXME: 是否需要这句？
//                        mCurrentUser.logout();
                        String regId = JPushInterface.getRegistrationID(mActivity.getApplicationContext());
                        url = url + "?AppOS=Android&RegistrationId=" + regId;
                        break;
                    case PATH.LOGOUT:
                        mCurrentUser.logout();
                        IntentUtils.toLogin(mActivity);
                        return true;
                }

                PageStatus pageStatus = new PageStatus(url, true, true, addLinkName, addLinkUrl, mCurrentUser.getToolbarBgColor());

                if (mFragment != null) {
                    // 从TabLayout发起的动作，可实现单个fragment刷新
                    IntentUtils.toNewGeneralActivity(mFragment, pageStatus);
                } else {
                    // 不是从TabLayout发起的动作，正常处理
                    IntentUtils.toNewGeneralActivity(mActivity, pageStatus);
                }

                return true;
            case "root":
                if (path.contains(PATH.LOGOUT)) {
                    mCurrentUser.logout();
                }
                mCurrentUser.setLink("");
                mCurrentUser.setChannelInfo("");

                IntentUtils.toMain(mActivity);
                return true;
            case "back":
                mActivity.finish();
                return true;
            case "backreload":
                if (mActivity instanceof GeneralActivity_) {
                    ((GeneralActivity_) mActivity).setBackReload();
                }
                mActivity.finish();

                if ("home_index".equalsIgnoreCase(pageName)) {
                    mCurrentUser.setLink("");
                    mCurrentUser.setChannelInfo("");
                    IntentUtils.toMain(mActivity, mCurrentUser.getCurrentTab());
                }
                return true;
            default:
                break;
        }

        // 全局登录页面处理
        switch (path) {
            case PATH.LOGIN:
            case PATH.LOGOUT:
                mCurrentUser.logout();
                IntentUtils.toLogin(mActivity);
                return true;
        }

        view.clearView();
        Map<String, String> cookies = new WeakHashMap<>();
        cookies.put("AppOS", "Android");

        view.loadUrl(url, cookies);
        // 当返回true时，控制网页在WebView中打开
        // 当返回false时，控制网页在系统自带的或第三方的浏览器中打开
        return true;
    }

    private boolean showStoragePermissionDialog() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(mActivity.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || mActivity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    ) {

                final NormalDialog dialog = new NormalDialog(mActivity);

                dialog.isTitleShow(false)
                        .btnNum(1)
                        .bgColor(Color.parseColor("#FFFFFF"))
                        .cornerRadius(5)
                        .content("无法使用相册\n请在\"设置\"中开启存储卡权限")
                        .contentGravity(Gravity.CENTER)
                        .contentTextSize(13)
                        .contentTextColor(Color.parseColor("#333333"))
                        .dividerColor(Color.parseColor("#CCCCCC"))
                        .btnText("确定")
                        .btnTextSize(15.5f)
                        .btnTextColor(Color.parseColor("#0092FF"))
                        .widthScale(0.7f)
                        .show();

                dialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
//                        IntentUtils.toSystemPermissionActivity(mActivity);
                        dialog.dismiss();
                    }
                });

                return true;
            }
        }

        return false;
    }

    private boolean showCameraPermissionDialog() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(mActivity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    ) {

                final NormalDialog dialog = new NormalDialog(mActivity);

                dialog.isTitleShow(false)
                        .btnNum(1)
                        .bgColor(Color.parseColor("#FFFFFF"))
                        .cornerRadius(5)
                        .content("无法使用相机\n请在\"设置\"中开启相机权限")
                        .contentGravity(Gravity.CENTER)
                        .contentTextSize(13)
                        .contentTextColor(Color.parseColor("#333333"))
                        .dividerColor(Color.parseColor("#CCCCCC"))
                        .btnText("确定")
                        .btnTextSize(15.5f)
                        .btnTextColor(Color.parseColor("#0092FF"))
                        .widthScale(0.7f)
                        .show();

                dialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
//                        IntentUtils.toSystemPermissionActivity(mActivity);
                        dialog.dismiss();
                    }
                });

                return true;
            }
        }

        return false;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        // 隐藏输入法
        Utils.UI.closeInputMethod(mActivity);

        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.clearFocus();

        if (mLoadingIndicator != null) {
            mLoadingIndicator.setVisibility(View.GONE);
        }
//        mWebView.setVisibility(View.VISIBLE);
//        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        if(!mWebView.getSettings().getLoadsImagesAutomatically()) {
            mWebView.getSettings().setLoadsImagesAutomatically(true);
        }

        if (mActivity instanceof GeneralActivity_) {
            ((GeneralActivity_) mActivity).checkWebView();
        } else if (mActivity instanceof MainActivity_) {
            ((MainActivity_) mActivity).checkWebView();
        }
    }

    private void handlePhoneAction(String url) {
        if ("tel:".equals(url)) {
            Utils.UI.showToastShort("联系号码未设置");
            return;
        }

        Intent intent = new Intent();
        intent.setData(Uri.parse(url));
        // 不要直接拨打，先跳转到拨号界面
        intent.setAction(Intent.ACTION_DIAL);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mActivity.startActivity(intent);
    }

    private void handleShareAction(String url) {
        url = url
                .replace("share:", "")
                .replace("Share:", "")
                .trim();

        url = url.replace("%", "%25");

        Uri uriShare = Uri.parse(BuildConfig.ENDPOINT + "?" + url);

        title = uriShare.getQueryParameter("Title");
        content = uriShare.getQueryParameter("Text");
        shareUrl = uriShare.getQueryParameter("ShareUrl");
        iconUrl = uriShare.getQueryParameter("IconUrl");

        if (iconUrl != null && !iconUrl.startsWith("http")) {
            iconUrl = BuildConfig.ENDPOINT + iconUrl;
        }

        timelineFun = uriShare.getQueryParameter("TimelineFun");
        timelineMode = uriShare.getQueryParameter("TimelineMode");

        if (!TextUtils.isEmpty(shareUrl) && shareUrl.startsWith("https")) {
            shareUrl = shareUrl.replace("https://", "http://");
        }

        if (!TextUtils.isEmpty(iconUrl) && iconUrl.startsWith("https")) {
            iconUrl = iconUrl.replace("https://", "http://");
        }

        sShareTitle = title;
        sShareContent = content;
        sShareUrl = shareUrl;
        sShareIconUrl = iconUrl;

        String attachData = uriShare.getQueryParameter("AttachData");

        Bundle bundle = new Bundle();
        bundle.putString("title",title);
        bundle.putString("content",content);
        bundle.putString("shareUrl",shareUrl);
        bundle.putString("iconUrl",iconUrl);
        bundle.putString("attachData",attachData);

        if ("link".equalsIgnoreCase(timelineMode)) {
            // 直接分享链接
            Intent intent = new Intent(mActivity, ShareLinkDialogActivity.class);
            intent.putExtra("message",bundle);
            mActivity.startActivity(intent);
        } else {
            //在这里弹出一个类似于分享的提示框，再根据选择的条目确定是分享图片还是分享链接
            Intent intent = new Intent(mActivity, ShareModeDialogActivity.class);
            intent.putExtra("message",bundle);
            mActivity.startActivity(intent);
        }

//        ShareUtils.showSharePanel(mActivity, title, content, shareUrl, iconUrl, timelineMode, timelineFun);
    }

    private void handleShareLinkAction() {
        if (!TextUtils.isEmpty(sShareTitle)
//                && !TextUtils.isEmpty(sShareContent)
                && !TextUtils.isEmpty(sShareUrl)) {
            ShareUtils.shareUrlToWeChatMoment(mActivity, sShareContent, sShareUrl, sShareIconUrl);
        }
//        sShareTitle = null;
//        sShareUrl = null;
//        sShareIconUrl = null;
    }

    private void handleShareMultiImagesAction() {
        List<String> list = null;

        if (mActivity instanceof GeneralActivity_) {
            list = ((GeneralActivity_) mActivity).getDownloadedImgList();
        } else if (mActivity instanceof MainActivity_) {
            list = ((MainActivity_) mActivity).getDownloadedImgList();
        }

        if (list != null) {
            // 多图分享
            ArrayList<Uri> imageUris = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                imageUris.add(Uri.fromFile(new File(list.get(i))));
            }

            try {
                Intent shareIntent = new Intent();
                shareIntent.setPackage("com.tencent.mm");
                shareIntent.setComponent(new ComponentName("com.tencent.mm",
                        "com.tencent.mm.ui.tools.ShareToTimeLineUI"));
                shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
//                String text = mTitle + " " + mShareUrl;
                String text = sShareContent;
                ArrayList<String> extraText = new ArrayList<>();
                extraText.add(text);
                shareIntent.putExtra(Intent.EXTRA_TEXT, extraText);
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, text);
                shareIntent.putExtra(Intent.EXTRA_TITLE, text);
                shareIntent.putExtra("Kdescription", text);
                shareIntent.setType("image/*");
                mActivity.startActivity(Intent.createChooser(shareIntent, sShareTitle));
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(mActivity, "分享失败！请先安装或打开微信", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void handlePayAction(String url) {
        url = url
                .replace("pay:", "")
                .replace("Pay:", "")
                .trim();
        Uri uri = Uri.parse(BuildConfig.ENDPOINT + "?" + url);
        String no = uri.getQueryParameter("AttachData");
        String payMethod = uri.getQueryParameter("PayMethod");
        PayUtils.handlePayAction(mActivity, mApiHelper, payMethod, no, mCurrentUser.getToolbarBgColor());
    }

    private void handleCopyAction(String url) {
        String text = url
                .replace("copy:", "")
                .replace("Copy:", "")
                .trim();
        try {
            text = URLDecoder.decode(text, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ClipboardManager clip = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
        clip.setPrimaryClip(ClipData.newPlainText(null, text));

        Utils.UI.showToastShort("内容已复制到剪贴板");
    }

    private void handleImageUploadAction(String url) {

        url = url
                .replace("upload:", "")
                .replace("Upload:", "")
                .trim();
        Uri uri = Uri.parse(BuildConfig.ENDPOINT + "?" + url);

        String attachData = uri.getQueryParameter("AttachData");
        String isMulti = uri.getQueryParameter("UploadMode");

        if (TextUtils.isEmpty(attachData)) {
            return;
        }

        mCurrentUser.setImageUploadAttachData(attachData);

        // 选取图片
        selectImage("multi".equals(isMulti.toLowerCase()));
    }

    private void handleImageOneKeySaveAllAction(String url) {
        url = url
                .replace("download:", "")
                .replace("Download:", "")
                .trim();
        Uri uri = Uri.parse(BuildConfig.ENDPOINT + "?" + url);

        String attachData = uri.getQueryParameter("AttachData");
        // 操作成功后的js回调函数
        String successFun = uri.getQueryParameter("SuccessFun");

        if (TextUtils.isEmpty(attachData)) {
            return;
        }

        DialogUtils.showImgOneKeySaveAllDialog(mActivity, mApiHelper, attachData, successFun);
    }

    private void handleImageSaveOneAction(String url) {
        url = url
                .replace("imagesave:", "")
                .replace("Imagesave:", "")
                .replace("imageSave:", "")
                .replace("ImageSave:", "")
                .replace("saveimage:", "")
                .replace("Saveimage:", "")
                .replace("saveImage:", "")
                .replace("SaveImage:", "")
                .replace("url=", "")
                .replace("Url=", "")
                .trim();

        if (!url.startsWith("http")) {
            url = BuildConfig.ENDPOINT + url;
        }
        DialogUtils.showImgSaveDialog(mActivity, url);
    }

    private void handleOpenPlayerAction(String url) {
        Intent intent = new Intent();
        intent.setClass(mActivity, AliyunPlayerActivity_.class);
        if (!TextUtils.isEmpty(url)) {
            intent.putExtra("url", url);
        }

        mActivity.startActivity(intent);
    }


    /**
     * 图片选择
     */
    private void selectImage(boolean isMultiSelect) {
        if (isMultiSelect) {
            MultiImageSelector.create()
                    .showCamera(true) // 是否显示相机. 默认为显示
                    .count(9) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                    .multi() // 多选模式, 默认模式;
                    .start(mActivity, REQUEST_IMAGE);
        } else {
            MultiImageSelector.create()
                    .showCamera(true) // 是否显示相机. 默认为显示
                    .single() // 单选模式
                    .start(mActivity, REQUEST_IMAGE);
        }
    }
}
